package com.example.mylibrarybase.yumengmeng19.ui;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;

import com.example.mylibrarybase.R;
import com.example.mylibrarybase.utils.LogUtils;

import java.util.List;

public class MainActivity_19_2 extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_19_2);
    }

    //判断 是否 关闭  APP 双击返回键  退出 APP
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
          //  dealWithIntent();
        }
        return super.onKeyDown(keyCode, event);
    }
    /**
     * 判断某一个类是否存在任务栈里面
     * @return
     */
    private boolean isExsitMianActivity(Class<?> cls){
        Intent intent = new Intent(this, cls);
        ComponentName cmpName = intent.resolveActivity(getPackageManager());
        boolean flag = false;
        if (cmpName != null) { // 说明系统中存在这个activity
            ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> taskInfoList = am.getRunningTasks(10);
            for (ActivityManager.RunningTaskInfo taskInfo : taskInfoList) {
                if (taskInfo.baseActivity.equals(cmpName)) { // 说明它已经启动了
                    flag = true;
                    break;  //跳出循环，优化效率
                }
            }
        }
        return flag;
    }
    /**
     * 进行逻辑处理
     */
    public void dealWithIntent(){
        if(isExsitMianActivity(MainActivity_19_1.class)){//存在这个类
            LogUtils.i("我先在任务站里面有1");
            //进行操作
        }else{//不存在这个类
            //进行操作
            LogUtils.i("我先在任务站里面没有1");
            MainActivity_19_2.this.finish();
            startActivity(new Intent(this, MainActivity_19_1.class));
        }
    }
}
